package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"hello/lib/mqttLib"
	"log"
	"strconv"
)

type DeviceStartStopController struct {
	beego.Controller
	PublicController
}

type RunStop struct {
	GatewayId string `json:"gateway_id"`
	UserId string `json:"user_id"`
	Params struct{
		Type string `json:"type"`
		Value string `json:"value"`
	} `json:"params"`
}
func (dc *DeviceStartStopController) Post() {
	reqData := dc.Ctx.Input.RequestBody
	var rs RunStop
	err := json.Unmarshal(reqData, &rs)
	if err != nil {
		log.Printf("Unmarshal data error : %s", err.Error())
	}
	if rs.Params.Type != "startStop" {
		log.Printf("")
		dc.response("error", "operation type error")
	}
	// 将设定值拼接为字符串，golang 在json序列化时存在当有不需要设定的值时，也会进行参数序列化，故采用字符串拼接方法。
	var params int
	switch rs.Params.Value {
	case "STOP_ALL":
		params = 0
	case "START_STIR":
		params = 255
	case "START_HEAT":
		params = 65280
	case "START_ALL":
		params = 65535
	}
	topic := rs.GatewayId + "/setting"
	//params := CLJBSetting{
	//	RunningStatus:     rs.Params.Value,
	//}
	//payload, err := json.Marshal(params)
	//if err != nil {
	//	log.Printf("Error : Marshal params error : %s", err.Error())
	//}
	setting_params := "{\"rs\":"+strconv.Itoa(params)+"}"
	payload := []byte(setting_params)
	c := mqttLib.NewMqttClient(mqttLib.DefaultMqttconfig, func(client mqtt.Client, msg mqtt.Message) {
		log.Print(msg)
	})
	c.Connect()
	defer c.Disconnect(10*1000)
	token := c.Publish(topic, 0, false, payload)
	if token.Error() != nil {
		log.Printf("Error : Publish message error : %s", token.Error().Error())
	}
}
